package com.ming.mallchat.common.chat.service.impl;

import com.ming.mallchat.common.chat.dao.RoomDao;
import com.ming.mallchat.common.chat.dao.RoomFriendDao;
import com.ming.mallchat.common.chat.enums.RoomTypeEnum;
import com.ming.mallchat.common.chat.pojo.Room;
import com.ming.mallchat.common.chat.pojo.RoomFriend;
import com.ming.mallchat.common.chat.service.RoomService;
import com.ming.mallchat.common.chat.service.adapter.ChatAdapter;
import com.ming.mallchat.common.common.domain.enums.NormalOrNoEnum;
import com.ming.mallchat.common.common.utils.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @author 86150
 * @description 针对表【room(房间表)】的数据库操作Service实现
 * @createDate 2023-10-11 17:04:41
 */
@Service
public class RoomServiceImpl implements RoomService {

    @Autowired
    private RoomFriendDao roomFriendDao;

    @Autowired
    private RoomDao roomDao;

    /**
     * 创建会话房间
     *
     * @param uidList
     */
    @Override
//    @Transactional(rollbackFor = Exception.class)
    public RoomFriend createFriendRoom(List<Long> uidList) {
        AssertUtil.isNotEmpty(uidList, "房间创建失败，好友数量不对");
        AssertUtil.equal(uidList.size(), 2, "房间创建失败，好友数量不对");
        String key = ChatAdapter.generateRoomKey(uidList);
        RoomFriend roomFriend = roomFriendDao.getByKey(key);
        if (Objects.nonNull(roomFriend)) {//如果房间存在，则恢复房间状态
            restoreRoomIfNeed(roomFriend);
        } else {
            Room room = createRoom();
            roomFriend = createRoomFriend(room.getId(),uidList);
        }
        return roomFriend;
    }

    /**
     * 禁用会话房间
     *
     * @param uidList
     */
    @Override
    public void disableFriendRoom(List<Long> uidList) {
        AssertUtil.isNotEmpty(uidList, "房间创建失败，好友数量不对");
        AssertUtil.equal(uidList.size(), 2, "房间创建失败，好友数量不对");
        roomFriendDao.disableRoom(ChatAdapter.generateRoomKey(uidList));
    }

    private RoomFriend createRoomFriend(Long id, List<Long> uidList) {
        RoomFriend roomFriend = ChatAdapter.buildFriendRoom(id,uidList);
        roomFriendDao.save(roomFriend);
        return roomFriend;
    }


    private Room createRoom() {
        Room insert = ChatAdapter.buildRoom(RoomTypeEnum.FRIEND);
        roomDao.save(insert);
        return insert;
    }

    private void restoreRoomIfNeed(RoomFriend roomFriend) {
        if (Objects.equals(roomFriend.getStatus(), NormalOrNoEnum.NOT_NORMAL.getStatus())) {
            roomFriendDao.restoreRoom(roomFriend.getId());
        }
    }
}




